package com.aube.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.aube.R;
import com.aube.control.DataManager;
import com.aube.model.OptionResultModel;
import com.aube.model.TimeLinePiece;
import com.aube.model.VoteInfo;
import com.aube.views.vote.AnimatorHelper;
import com.aube.views.vote.IVoteProxy;
import com.aube.views.vote.SupportView;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UmengUtils;

/**
 * Created by huyaonan on 16/3/22.
 */
public class CardVSNew extends BaseCardNew implements IVoteProxy {

    private Context context;

    private View mGoodsLayout, mRoot;
    private int margin=0;
    private int marginBottom=0;

    private ImageView mLogo;
    private TextView mTitle;

    private SupportView supportView;
    private ViewGroup mGroup;

    private VoteInfo mVoteInfo;

    private View mClose, mTop;

    private int selectedIndex = -1;

    public CardVSNew(Context context) {
        this(context, null);
    }
    public CardVSNew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public CardVSNew(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

        mRoot = LayoutInflater.from(getContext()).inflate(R.layout.layout_card_vs_new, this);

        mLogo = (ImageView) mRoot.findViewById(R.id.card_vs_logo);
        mTitle = (TextView) mRoot.findViewById(R.id.card_vs_title);

        mGoodsLayout = findViewById(R.id.card_vs_layout);

        mCollapse = (ImageView) findViewById(R.id.card_vs_collapse);

        mClose = findViewById(R.id.card_vs_close);
        mClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });

        mTop = findViewById(R.id.card_vs_top);
        mTop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGroup.getVisibility() != View.VISIBLE) {
                    swithWindow(false, mGroup);
                }
            }
        });

        mGroup = (ViewGroup) findViewById(R.id.card_vs);

        mCollapse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                swithWindow(mGroup.getVisibility() == View.VISIBLE, mGroup);
                requestLayout();
            }
        });

        margin = getResources().getDimensionPixelOffset(R.dimen.card_margin_space);
        marginBottom = getResources().getDimensionPixelOffset(R.dimen.card_margin_bottom);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int screenWidth = SysUtil.getScreenWidth(context);
        int widthSpec = MeasureSpec.makeMeasureSpec(screenWidth*3/4, MeasureSpec.EXACTLY);

        super.onMeasure(widthSpec, heightMeasureSpec);

        int height = mGoodsLayout.getMeasuredHeight() + marginBottom;
        int width = mGoodsLayout.getMeasuredWidth() + margin*2;

        mGroup.measure(widthMeasureSpec, 0);
        mContentHeight = mGroup.getMeasuredHeight();

        measureChild(getChildAt(0), MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));

        setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
//        measureChild(getChildAt(0), MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - margin, MeasureSpec.EXACTLY));
//
//        setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    }

    public void fillData(final TimeLinePiece item) {
        this.mData = item;
        mTitle.setText(item.title);
        if(StringUtils.isNotBlank(item.getImgUrl())) {
            ImageLoader.getInstance(context).fillImage(mLogo, item.getImgUrl());
        } else {
            mLogo.setVisibility(View.GONE);
            ImageLoader.getInstance(context).preloadBitmap(item.getImgTag(), new ImageLoader.IPreloadCallback<Bitmap>() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    if (bitmap == null)
                        return;

                    SpannableStringBuilder builder = new SpannableStringBuilder("[star]  " + item.title);
                    builder.setSpan(new ExtendImageSpan(getContext(), bitmap, getTextHeight()), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mTitle.setText(builder);
                }

                @Override
                public void onFail() {

                }
            });
        }
        selectedIndex = DataManager.getInstance(context).getIndex(mData.rid);
        setPKInfo(parse(item));

        if(item.isCardFold()) {
            mGroup.setVisibility(View.GONE);
            mCollapse.setImageResource(R.drawable.icon_arrowup);
        } else {
            mCollapse.setImageResource(R.drawable.icon_arrowdown);
        }

        UmengUtils.reportUmengEvent(context, UmengUtils.SHOW_PK, UmengUtils.appendLabels(mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));
    }

    private float getTextHeight() {
        Paint paint = mTitle.getPaint();
        return Math.abs(paint.ascent());
    }

    private VoteInfo parse(TimeLinePiece item) {
        VoteInfo info = new VoteInfo();
        info.setup(getContext(), item);
        return info;
    }

    public void init(TimeLinePiece data, ChannelDetail detail) {
        super.init(data, detail);
        fillData(data);
    }

    @Override
    public String getType() {
        return TYPE_PK;
    }

    @Override
    public void doNext() {
        if(iSender != null)
            iSender.startSync(mData.rid, false);
    }

    private void setPKInfo(VoteInfo voteInfo) {
        try {
            this.mVoteInfo = voteInfo;
            if (voteInfo.getContents() != null && voteInfo.getContents().size() >= 2) {
                View view = LayoutInflater.from(context).inflate(R.layout.layout_vs, mGroup, false);
                supportView = (SupportView) view.findViewById(R.id.view_support);
                supportView.init();
                supportView.setIVoteProxy(this);
                supportView.setVoteInfo(voteInfo, true);

                ((TextView) view.findViewById(R.id.text_title_red)).setText(voteInfo.getContents().get(0).getSubject());
                ((TextView) view.findViewById(R.id.text_title_blue)).setText(voteInfo.getContents().get(1).getSubject());
                mGroup.addView(view);
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClickListener(View view, int position) {
        if(mData == null || !mData.isIllegal)
            return;

//        boolean isRed = false;
//        switch (view.getId()) {
//            case R.id.btn_vote_red:
//                isRed = true;
//                position = 0;
//                break;
//            case R.id.btn_vote_blue:
//                position = 1;
//                break;
//            default:
//                break;
//        }
        boolean isRed = position == 0;

        String optionId = mData.getOptionId(position);
        String cancelId = null;
        if(selectedIndex >= 0)
            cancelId = mData.getOptionId(selectedIndex);
        if(selectedIndex == position)
            optionId = null;
        report(mData.rid, optionId, cancelId, true);

        DataManager.getInstance(context).updateOptionCount(cancelId, true);
        DataManager.getInstance(context).updateOptionCount(optionId, false);
        mVoteInfo.update(context);

//        mVoteInfo.update(getContext(), position, selectedIndex);

        if (selectedIndex == position)
            selectedIndex = -1;
        else
            selectedIndex = position;

        UmengUtils.reportUmengEvent(context, UmengUtils.TO_PK, UmengUtils.appendLabels(mData.getOptionValue(position), mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));

        DataManager.getInstance(context).update(mData.rid, selectedIndex);

        supportView.setVoteInfo(mVoteInfo, true);
        boolean selected = (boolean) view.getTag(R.id.vs_selected_state);

        AnimatorHelper.voteAnimation((ImageButton) view, selected, isRed);
    }

    @Override
    public void syncData(OptionResultModel response) {
//        mVoteInfo.update(context, response);
        mVoteInfo.update(context);
        supportView.setVoteInfo(mVoteInfo, true);
    }

}
